package jmind.core.js;

import java.io.BufferedReader;
import java.io.IOException;
import java.io.InputStreamReader;
import java.util.HashMap;
import java.util.Map;

/***
 * 自己实现读取文件，解析js
 * 只支持a=function(s){} 格式，并且函数之间必须用 /*** 的 注释 进行分割
 */
public class ParseScript extends JavaScript {

    private final String comment = "/\\*.*?\\*/";

    public static void main(String[] args) {
        ParseScript script = new ParseScript("reduce.js");
        System.out.println(script.getFunctionContent("mapMonitor"));
    }

    private Map<String, String> map = new HashMap<String, String>();

    public ParseScript(String name) {
        BufferedReader in = new BufferedReader(new InputStreamReader(load(name)));
        StringBuffer buffer = new StringBuffer();
        String line = null;
        try {
            while ((line = in.readLine()) != null) {
                int a = line.indexOf("//");
                if (a > -1) {
                    line = line.substring(0, a);
                }
                buffer.append(line.trim());
            }
        } catch (IOException e) {
            // TODO Auto-generated catch block
            e.printStackTrace();
        }
        String[] content = buffer.toString().split(comment);
        for (String s : content) {
            int i = s.indexOf("=function(");
            if (i > 0) {
                map.put(s.substring(0, i), s.substring(i + 1));
            }
        }

    }

    @Override
    public Object eval(String name) {
        // TODO Auto-generated method stub
        return null;
    }

    @Override
    public Object invokeMethod(String name, Object... args) throws Exception {
        return null;
    }

    @Override
    public String getFunctionContent(String functionName) {
        // TODO Auto-generated method stub
        return map.get(functionName);
    }

}
